<template>
  <div class="game-container">
    <el-container>
      <el-header class="mobile-header">
        <div class="header-content">
          <div class="room-info">
            <h2>房间号：{{ roomCode }}</h2>
            <el-tag :type="getStatusType(roomStatus)">
              {{ getStatusText(roomStatus) }}
            </el-tag>
          </div>
          <div class="user-info">
            <el-button 
              v-if="roomStatus === 'PLAYING' && Object.keys(roundScores).length > 0"
              type="primary" 
              size="small"
              @click="showResultDialog = true"
            >
              查看结算
            </el-button>
            <el-dropdown @command="handleCommand">
              <span class="user-dropdown">
                {{ userInfo?.nickname }}
                <el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="leave">离开房间</el-dropdown-item>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      
      <el-main class="mobile-main">
        <div class="game-table">
          <!-- 游戏状态 -->
          <div class="game-status">
            <el-tag type="info" v-if="roomStatus === 'PLAYING'">{{ currentRound }}/{{ totalRounds }}</el-tag>
            <el-tag type="success" v-if="isMyTurn">轮到你了</el-tag>
            <el-tag type="warning" v-if="roomStatus === 'WAITING'">
              等待玩家准备 ({{ readyPlayersCount }}/{{ totalPlayers }})
            </el-tag>
          </div>

          <!-- 当前玩家区域 -->
          <div class="current-player">
            <div class="player-info compact-info">
              <span class="user-nickname">{{ userInfo?.nickname }}</span>
              <div class="user-stats">
                <el-tag size="small">{{ userInfo?.score }}</el-tag>
                <el-tag :type="isReady ? 'success' : 'info'" size="small">
                  {{ isReady ? '已准备' : '未准备' }}
                </el-tag>
              </div>
            </div>
            
            <!-- 移动端优化：使用手风琴组件 -->
            <el-collapse v-model="activeCollapse" class="mobile-collapse" :accordion="false">
              <!-- 手牌区域 - 增大区域 -->
              <el-collapse-item name="cards" class="collapse-section">
                <template #title>
                  <div class="section-title">
                    <span>可选牌 ({{ remainingCards.length }}张)</span>
                    <el-tag size="small" type="info">点击选择</el-tag>
                  </div>
                </template>
                <div class="player-cards ultra-compact-cards enhanced-card-area">
                  <template v-if="roomStatus === 'PLAYING'">
                    <div class="cards-container mini-cards">
                      <PokerCard 
                        v-for="(card, index) in remainingCards" 
                        :key="index" 
                        :card="card"
                        :selected="isCardSelected(card)"
                        :size="'mini'"
                        @click="toggleCardSelection(card)"
                      />
                    </div>
                  </template>
                </div>
              </el-collapse-item>
              
              <!-- 墩位区域 -->
              <el-collapse-item name="hands" class="collapse-section">
                <template #title>
                  <div class="section-title">
                    <span>墩位组合</span>
                    <el-tag size="small" :type="canSubmitHands ? 'success' : 'warning'">
                      {{ canSubmitHands ? '可提交' : '待完成' }}
                    </el-tag>
                  </div>
                </template>
                <div class="player-hands ultra-compact-hands">
                  <div class="hand-section" 
                       :class="{ 'selected': currentHand === 'front' }"
                       @click="selectHand('front')"
                  >
                    <h3>前墩 <span class="hand-count">{{ frontHand.length }}/3</span></h3>
                    <div class="cards-container mini-cards">
                      <PokerCard 
                        v-for="(card, index) in frontHand" 
                        :key="index" 
                        :card="card"
                        :size="'mini'"
                        @click.stop="removeFromHand(card, 'front')"
                      />
                    </div>
                  </div>
                  <div class="hand-section"
                       :class="{ 'selected': currentHand === 'middle' }"
                       @click="selectHand('middle')"
                  >
                    <h3>中墩 <span class="hand-count">{{ middleHand.length }}/5</span></h3>
                    <div class="cards-container mini-cards">
                      <PokerCard 
                        v-for="(card, index) in middleHand" 
                        :key="index" 
                        :card="card"
                        :size="'mini'"
                        @click.stop="removeFromHand(card, 'middle')"
                      />
                    </div>
                  </div>
                  <div class="hand-section"
                       :class="{ 'selected': currentHand === 'back' }"
                       @click="selectHand('back')"
                  >
                    <h3>后墩 <span class="hand-count">{{ backHand.length }}/5</span></h3>
                    <div class="cards-container mini-cards">
                      <PokerCard 
                        v-for="(card, index) in backHand" 
                        :key="index" 
                        :card="card"
                        :size="'mini'"
                        @click.stop="removeFromHand(card, 'back')"
                      />
                    </div>
                  </div>
                </div>
              </el-collapse-item>
              
              <!-- 牌型列表区域 -->
              <el-collapse-item name="handTypes" class="collapse-section" v-if="roomStatus === 'PLAYING'">
                <template #title>
                  <div class="section-title">
                    <span>牌型列表</span>
                    <el-tag size="small" type="info">可用牌型: {{ availableHandTypesCount }}</el-tag>
                  </div>
                </template>
                <div class="possible-hands ultra-compact-hands">
                  <div class="hand-types-grid">
                    <div 
                      v-for="type in Object.values(HandType).filter((t): t is HandType => typeof t === 'number' && t !== HandType.HIGH_CARD)" 
                      :key="type" 
                      class="hand-type-item tiny-hand-type"
                      :class="{ 'available': hasHandType(type) }"
                      @click="hasHandType(type) && selectHandType(type)"
                    >
                      <span class="hand-type-name">{{ getHandTypeText(type) }}</span>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>

            <div class="player-actions">
              <template v-if="roomStatus === 'WAITING'">
                <div v-if="currentRound > 1" class="next-round-reminder">
                  <el-alert
                    title="回合结束"
                    type="info"
                    :description="`第${currentRound-1}回合已结束，请准备开始第${currentRound}回合`"
                    show-icon
                    :closable="false"
                  />
                </div>
                <el-button type="primary" @click="handleReady" v-if="!isReady">
                  {{ currentRound > 1 ? '准备下一回合' : '准备' }}
                </el-button>
                <el-button type="warning" @click="handleCancelReady" v-else>取消准备</el-button>
                <el-button type="success" @click="handleStartGame" v-if="isCreator && readyPlayersCount === totalPlayers && totalPlayers >= 2 && currentRound === 1">开始游戏</el-button>
              </template>
              <template v-if="roomStatus === 'PLAYING'">
                <div v-if="hasSubmittedThisRound" class="submitted-hint">
                  <el-tag type="success">已提交本回合牌型</el-tag>
                  <p class="hint-text">请等待其他玩家提交，或等待下一回合开始</p>
                </div>
                <div v-else class="action-buttons">
                  <el-button 
                    type="success" 
                    @click="submitHands" 
                    :disabled="!canSubmitHands"
                  >
                    提交牌型
                  </el-button>
                  <el-button 
                    type="warning" 
                    @click="resetAllHands"
                    v-if="hasAnyCards"
                  >
                    重选所有
                  </el-button>
                </div>
              </template>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 结算结果对话框 -->
    <el-dialog
      v-model="showResultDialog"
      title="回合结算"
      width="400px"
      :before-close="closeResultDialog"
      class="settlement-dialog"
      :append-to-body="true"
      center
      fullscreen-on-mobile
    >
      <div class="result-content">
        <div class="result-header">
          <h4 class="result-round">第 {{ currentRound }} 回合结算</h4>
          <div class="round-indicator">
            <span>{{ currentRound }}</span> / {{ totalRounds }}
          </div>
        </div>
        
        <transition-group name="list" tag="div" class="players-list">
          <div v-for="(result, index) in gameResult" :key="result.id" 
               class="result-item" 
               :class="{'first-place': index === 0, 'current-player': result.id === userInfo?.id}">
            <div class="player-rank">{{ index + 1 }}</div>
            <div class="player-info">
              <span class="nickname">{{ result.nickname }}</span>
              <span class="score">{{ result.score }}</span>
            </div>
            <div class="round-score" :class="{'positive': result.roundScore > 0, 'negative': result.roundScore < 0}">
              {{ result.roundScore > 0 ? '+' : '' }}{{ result.roundScore }}
            </div>
          </div>
        </transition-group>
        
        <div class="next-round-info" v-if="currentRound < totalRounds">
          <span>下一回合将在 5 秒后开始准备阶段</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeResultDialog" type="primary">关闭</el-button>
          <el-button 
            v-if="roomStatus === 'WAITING' && !isReady && currentRound > 1"
            type="success" 
            @click="readyNextRound"
          >
            准备下一回合
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 游戏开始提示 -->
    <div v-if="showGameStartDialog" class="game-start-notification">
      <div class="game-start-text">游戏开始</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { 
  HandType, getHandTypeText, getRankValue, evaluateHand,
  getPossibleHands, validateHands, findStraightFlush, findRoyalFlush, getHandType
} from '@/utils/poker'
import type { Card } from '@/types/card'
import type { Player } from '@/types'
import { roomApi } from '@/api/room'
import { userApi } from '@/api/user'
import { useWebSocket } from '@/composables/useWebSocket'
import type { RoomStatus } from '@/api/room'
import PokerCard from '@/components/Card.vue'
import type { UserInfo } from '@/types/user'

interface PlayerData {
  id: number
  nickname: string
  score: number
  ready: boolean
  cards?: Card[]
  cardsCount?: number
}

interface Arrangement {
  front: Card[]
  middle: Card[]
  back: Card[]
}

interface Props {
  roomCode: string
  roomStatus: RoomStatus | null
}

const props = defineProps<Props>()
const router = useRouter()
const route = useRoute()
const roomCode = ref(route.params.roomCode as string)
const userInfo = ref<any>(null)
const roomStatus = ref<'WAITING' | 'PLAYING' | 'FINISHED'>('WAITING')
const otherPlayers = ref<PlayerData[]>([])
const currentRound = ref(1)
const totalRounds = ref(13)
const isMyTurn = ref(false)
const isReady = ref(false)
const readyPlayersCount = ref(0)
const totalPlayers = ref(0)
const myCards = ref<Card[]>([])
const selectedCards = ref<Card[]>([])
const lastPlayedCards = ref<Card[]>([])
const isCreator = ref(false)
const frontHand = ref<Card[]>([])
const middleHand = ref<Card[]>([])
const backHand = ref<Card[]>([])
const currentHand = ref<'front' | 'middle' | 'back' | null>(null)

// 添加一个变量来记录当前选择的牌型组合索引
const currentHandTypeIndex = ref<Map<HandType, number>>(new Map());

// 添加变量记录当前回合是否已提交
const hasSubmittedThisRound = ref(false);

// 添加游戏开始提示相关变量
const showGameStartDialog = ref(false);
// 添加标记，记录是否已经显示过游戏开始提示
const showGameStartedFlag = ref(false);

const remainingCards = computed(() => {
  const usedCards = new Set([
    ...frontHand.value,
    ...middleHand.value,
    ...backHand.value
  ].map(card => `${card.suit}-${card.rank}`));
  
  return myCards.value
    .filter(card => !usedCards.has(`${card.suit}-${card.rank}`))
    .sort((a, b) => getRankValue(a.rank) - getRankValue(b.rank));
});

const canSubmitHands = computed(() => {
  return frontHand.value.length === 3 && 
         middleHand.value.length === 5 && 
         backHand.value.length === 5;
});

const selectHand = (hand: 'front' | 'middle' | 'back') => {
  if (currentHand.value === hand) {
    currentHand.value = null;
    return;
  }
  
  currentHand.value = hand;
  
  // 检查选中的牌是否符合当前墩位的要求
  const maxCards = hand === 'front' ? 3 : 5;
  if (selectedCards.value.length === maxCards) {
    // 对选中的牌进行排序
    const sortedCards = [...selectedCards.value].sort((a, b) => getRankValue(a.rank) - getRankValue(b.rank));
    
    // 将选中的牌移动到对应的墩位
    switch (hand) {
      case 'front':
        frontHand.value = sortedCards;
        break;
      case 'middle':
        middleHand.value = sortedCards;
        break;
      case 'back':
        backHand.value = sortedCards;
        break;
    }
    // 清空选择
    selectedCards.value = [];
    currentHand.value = null;
    
    // 重新计算可能的牌型
    const possibleHands = getPossibleHands(remainingCards.value);
    
    // 按牌型分组
    const handsByType = new Map<HandType, Array<{ cards: Card[]; score: number }>>();
    possibleHands.forEach(hand => {
      if (!handsByType.has(hand.type)) {
        handsByType.set(hand.type, []);
      }
      handsByType.get(hand.type)?.push({ cards: hand.cards, score: hand.score });
    });
    
    // 转换为数组并排序
    const sortedHands = Array.from(handsByType.entries())
      .map(([type, hands]) => ({
        type,
        hands: hands.sort((a, b) => b.score - a.score)
      }))
      .sort((a, b) => b.type - a.type);
    
    // 更新可能的牌型
    possibleHandTypes.value = sortedHands;
  }
};

const removeFromHand = (card: Card, hand: 'front' | 'middle' | 'back') => {
  switch (hand) {
    case 'front':
      frontHand.value = frontHand.value.filter(c => c !== card);
      break;
    case 'middle':
      middleHand.value = middleHand.value.filter(c => c !== card);
      break;
    case 'back':
      backHand.value = backHand.value.filter(c => c !== card);
      break;
  }
  
  // 从手牌中移除后，将其添加回可选牌中
  if (!selectedCards.value.some(c => c.suit === card.suit && c.rank === card.rank)) {
    selectedCards.value.push(card);
  }
  
  // 重新计算可能的牌型
  const possibleHands = getPossibleHands(remainingCards.value);
  
  // 按牌型分组
  const handsByType = new Map<HandType, Array<{ cards: Card[]; score: number }>>();
  possibleHands.forEach(hand => {
    if (!handsByType.has(hand.type)) {
      handsByType.set(hand.type, []);
    }
    handsByType.get(hand.type)?.push({ cards: hand.cards, score: hand.score });
  });
  
  // 转换为数组并排序
  const sortedHands = Array.from(handsByType.entries())
    .map(([type, hands]) => ({
      type,
      hands: hands.sort((a, b) => b.score - a.score)
    }))
    .sort((a, b) => b.type - a.type);
  
  // 更新可能的牌型
  possibleHandTypes.value = sortedHands;
};

const submitHands = async () => {
  try {
    // 检查是否已经提交过本轮牌型
    if (hasSubmittedThisRound.value) {
      ElMessage.warning('本回合已提交过牌型，请等待下一回合');
      return;
    }
    
    if (!validateHands(frontHand.value, middleHand.value, backHand.value)) {
      ElMessage.error('牌型不合法，请重新选择');
      return;
    }
    
    await roomApi.submitHand(roomCode.value, {
      frontHand: frontHand.value,
      middleHand: middleHand.value,
      backHand: backHand.value
    });
    
    // 标记为已提交本轮牌型
    hasSubmittedThisRound.value = true;
    
    ElMessage.success('提交牌型成功');
    
    // 立即获取一次房间状态
    await getRoomStatus();
    
    // 增加等待时间到2000ms
    setTimeout(async () => {
      try {
        const result = await roomApi.getRoomStatus(roomCode.value);
        if (result && result.data) {
          const allPlayersReady = result.data.players.every((p: any) => p.ready);
          
          // 显示结算结果对话框
          if (allPlayersReady && result.data.roundScores && Object.keys(result.data.roundScores).length > 0) {
            roundScores.value = result.data.roundScores;
            
            // 构建结算结果数据
            gameResult.value = result.data.players.map((p: any) => ({
              id: p.id,
              nickname: p.nickname,
              score: p.score,
              roundScore: result.data.roundScores?.[p.id] || 0
            })).sort((a: {score: number}, b: {score: number}) => b.score - a.score); // 按总分降序排序
            
            // 强制显示结算对话框
            console.log("提交后检查到所有玩家已准备，显示结算结果", gameResult.value);
            showResultDialog.value = true;
          }
        }
      } catch (error) {
        console.error('延迟获取房间状态失败:', error);
      }
    }, 2000); // 延迟更改为2秒，给服务器更多时间处理
  } catch (error: any) {
    console.error('提交牌型失败:', error);
    ElMessage.error(error.response?.data?.message || '提交牌型失败，请重试');
  }
};

// 获取用户信息
const getUserInfo = async () => {
  try {
    const result = await userApi.getUserInfo()
    if (result && result.data) {
      userInfo.value = {
        ...result.data,
        score: 0
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 添加结算结果相关的变量
const showResultDialog = ref(false);
const roundScores = ref<{[key: number]: number}>({});
const allSubmitted = ref(false);
const gameResult = ref<Array<{id: number, nickname: string, score: number, roundScore: number}>>([]);

// 结算提示音
const settlementSound = ref<HTMLAudioElement | null>(null);

// 修改获取房间状态的函数，添加处理比牌结果的逻辑
const getRoomStatus = async () => {
  try {
    const result = await roomApi.getRoomStatus(roomCode.value)
    if (result && result.data) {
      const prevStatus = roomStatus.value;
      const prevReadyCount = readyPlayersCount.value;
      const prevRound = currentRound.value;
      
      // 当游戏状态从PLAYING变为WAITING且是第一回合时，重置标记
      if (prevStatus === 'PLAYING' && result.data.status === 'WAITING' && result.data.currentRound === 1) {
        console.log("重置游戏开始提示标记");
        showGameStartedFlag.value = false;
      }
      
      // 检查是否为游戏开始的状态：第一回合且状态为PLAYING
      if (result.data.status === 'PLAYING' && result.data.currentRound === 1) {
        // 如果是新状态(从等待到游戏中)或初次加载游戏
        if (prevStatus === 'WAITING' || (prevStatus === 'PLAYING' && !showGameStartedFlag.value)) {
          console.log("显示游戏开始提示 (getRoomStatus)");
          showGameStartDialog.value = true;
          setTimeout(() => {
            showGameStartDialog.value = false;
          }, 1000); // 1秒后自动关闭
          
          // 标记已经显示过游戏开始提示
          showGameStartedFlag.value = true;
        }
      }
      
      roomStatus.value = result.data.status
      otherPlayers.value = result.data.players.filter((p: any) => p.id !== userInfo.value?.id)
      readyPlayersCount.value = result.data.readyPlayersCount || 0
      totalPlayers.value = result.data.totalPlayers || 0
      
      // 记录当前回合的变更
      const newRound = result.data.currentRound || 1;
      
      // 如果进入了新的回合，重置提交状态和清空墩位
      if (newRound > prevRound) {
        console.log(`回合变更: ${prevRound} -> ${newRound}，重置牌型选择`);
        hasSubmittedThisRound.value = false;
        resetAllHands();
      }
      
      currentRound.value = newRound;
      totalRounds.value = result.data.totalRounds || 13;
      
      // 检查是否所有玩家都已提交牌型
      const allPlayersReady = result.data.players.every((p: any) => p.ready);
      
      // 如果所有玩家都已准备且结算数据存在
      if (allPlayersReady && result.data.roundScores && Object.keys(result.data.roundScores).length > 0) {
        roundScores.value = result.data.roundScores;
        
        // 构建结算结果数据
        gameResult.value = result.data.players.map((p: any) => ({
          id: p.id,
          nickname: p.nickname,
          score: p.score,
          roundScore: result.data.roundScores?.[p.id] || 0
        })).sort((a: {score: number}, b: {score: number}) => b.score - a.score); // 按总分降序排序
        
        console.log("所有玩家准备好了，显示结算结果", gameResult.value);
        
        // 修改：当所有玩家准备好了且有得分数据时，始终显示结算结果
        if (roomStatus.value === 'PLAYING' && 
            allPlayersReady && 
            Object.keys(result.data.roundScores).length > 0) {
          showResultDialog.value = true;
        }
      }
      
      const currentPlayer = result.data.players.find((p: any) => p.id === userInfo.value?.id)
      if (currentPlayer) {
        isReady.value = currentPlayer.ready || false
        isCreator.value = result.data.players[0].id === userInfo.value?.id
        
        // 如果当前玩家已准备，标记为已提交本轮牌型
        if (isReady.value && roomStatus.value === 'PLAYING') {
          hasSubmittedThisRound.value = true;
        }
        
        if (roomStatus.value === 'PLAYING') {
          myCards.value = currentPlayer.cards || []
          lastPlayedCards.value = result.data.lastPlayedCards || []
          isMyTurn.value = result.data.currentPlayerId === userInfo.value?.id
          
          // 计算可能的牌型
          if (myCards.value.length > 0) {
            const possibleHands = getPossibleHands(myCards.value);
            
            // 按牌型分组
            const handsByType = new Map<HandType, Array<{ cards: Card[]; score: number }>>();
            possibleHands.forEach(hand => {
              if (!handsByType.has(hand.type)) {
                handsByType.set(hand.type, []);
              }
              handsByType.get(hand.type)?.push({ cards: hand.cards, score: hand.score });
            });
            
            // 转换为数组并排序
            const sortedHands = Array.from(handsByType.entries())
              .map(([type, hands]) => ({
                type,
                hands: hands.sort((a, b) => b.score - a.score)
              }))
              .sort((a, b) => b.type - a.type);
            
            // 更新可能的牌型
            possibleHandTypes.value = sortedHands;
          }
        }
      }
      
      // 检查自己是否在房间中
      const playerInRoom = result.data.players.some((p: any) => p.id === userInfo.value?.id);
      if (!playerInRoom && result.data.status !== 'WAITING') {
        ElMessage({
          message: "您已不在房间中，将返回首页",
          type: "warning",
          duration: 5000
        });
        router.push('/home');
      }
    }
  } catch (error) {
    console.error("获取房间状态失败:", error);
    ElMessage({
      message: "获取房间状态失败，将返回首页",
      type: "error",
      duration: 5000
    });
    setTimeout(() => {
      router.push('/home');
    }, 1000);
  }
}

// 添加准备下一回合的方法
const readyNextRound = async () => {
  try {
    await roomApi.ready(roomCode.value);
    isReady.value = true;
    ElMessage.success('已准备下一回合');
    closeResultDialog();
  } catch (error) {
    console.error('准备下一回合失败:', error);
    ElMessage.error('准备失败，请重试');
  }
}

// 离开房间
const handleLeaveRoom = async () => {
  try {
    await ElMessageBox.confirm('确定要离开房间吗？', '提示', {
      type: 'warning'
    })
    await roomApi.leaveRoom(roomCode.value)
    ElMessage.success('已离开房间')
    router.push('/home')
  } catch (error) {
    console.error('离开房间失败:', error)
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    const result = await userApi.logout()
    localStorage.removeItem('token')
    ElMessage.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
  }
}

// 处理下拉菜单命令
const handleCommand = async (command: string) => {
  if (command === 'leave') {
    await handleLeaveRoom()
  } else if (command === 'logout') {
    await handleLogout()
  }
}

// 处理准备
const handleReady = async () => {
  try {
    await roomApi.ready(roomCode.value)
    isReady.value = true
    ElMessage.success('准备成功')
    getRoomStatus() // 更新房间状态
  } catch (error) {
    console.error('准备失败:', error)
    ElMessage.error('准备失败，请重试')
  }
}

// 处理取消准备
const handleCancelReady = async () => {
  try {
    await roomApi.cancelReady(roomCode.value)
    isReady.value = false
    ElMessage.success('已取消准备')
    getRoomStatus() // 更新房间状态
  } catch (error) {
    console.error('取消准备失败:', error)
    ElMessage.error('取消准备失败，请重试')
  }
}

// 处理开始游戏
const handleStartGame = async () => {
  try {
    await roomApi.startGame(roomCode.value)
    ElMessage.success('游戏开始')
    showGameStartDialog.value = true; // 房主直接显示提示
    setTimeout(() => {
      showGameStartDialog.value = false;
    }, 1000);
    
    // 标记已经显示过游戏开始提示
    showGameStartedFlag.value = true;
    
    getRoomStatus() // 更新房间状态
  } catch (error: any) {
    console.error('开始游戏失败:', error)
    ElMessage.error(error.response?.data?.message || '开始游戏失败，请重试')
  }
}

// 检查卡牌是否被选中
const isCardSelected = (card: Card): boolean => {
  return selectedCards.value.some(c => c.suit === card.suit && c.rank === card.rank);
};

// 选择卡牌
const toggleCardSelection = (card: Card) => {
  // 如果当前正在选择某个墩位
  if (currentHand.value) {
    const hand = currentHand.value;
    const maxCards = hand === 'front' ? 3 : 5;
    
    // 如果已经选择了最大数量的牌，且这张牌没有被选中，则不允许选择
    if (selectedCards.value.length >= maxCards && !isCardSelected(card)) {
      return;
    }
  }
  
  if (isCardSelected(card)) {
    selectedCards.value = selectedCards.value.filter(c => 
      !(c.suit === card.suit && c.rank === card.rank)
    );
  } else {
    selectedCards.value.push(card);
  }
  
  // 对选中的牌进行排序
  selectedCards.value.sort((a, b) => getRankValue(a.rank) - getRankValue(b.rank));
  
  // 重新计算可能的牌型
  const possibleHands = getPossibleHands(remainingCards.value);
  
  // 按牌型分组
  const handsByType = new Map<HandType, Array<{ cards: Card[]; score: number }>>();
  possibleHands.forEach(hand => {
    if (!handsByType.has(hand.type)) {
      handsByType.set(hand.type, []);
    }
    handsByType.get(hand.type)?.push({ cards: hand.cards, score: hand.score });
  });
  
  // 转换为数组并排序
  const sortedHands = Array.from(handsByType.entries())
    .map(([type, hands]) => ({
      type,
      hands: hands.sort((a, b) => b.score - a.score)
    }))
    .sort((a, b) => b.type - a.type);
  
  // 更新可能的牌型
  possibleHandTypes.value = sortedHands;
};

// 牌型选择相关
const showHandTypeDialog = ref(false)
const possibleHandTypes = ref<Array<{
  type: HandType
  hands: Array<{ cards: Card[]; score: number }>
}>>([])

// 已选择的牌
const selectedFrontHand = ref<Card[]>([])
const selectedMiddleHand = ref<Card[]>([])
const selectedBackHand = ref<Card[]>([])

// 检查牌型是否已被选择
const isHandSelected = (cards: Card[]): boolean => {
  return cards.some(card => isCardSelected(card))
}

// 更新已选择的牌
const updateSelectedCards = () => {
  // 更新前墩
  if (selectedFrontHand.value.length === 3) {
    frontHand.value = [...selectedFrontHand.value]
  }
  
  // 更新中墩
  if (selectedMiddleHand.value.length === 5) {
    middleHand.value = [...selectedMiddleHand.value]
  }
  
  // 更新后墩
  if (selectedBackHand.value.length === 5) {
    backHand.value = [...selectedBackHand.value]
  }
}

// 选择牌型
const selectHandType = (type: HandType) => {
  console.log(`选择牌型: ${getHandTypeText(type)}`);
  
  // 为顺子增加特殊处理
  if (type === HandType.STRAIGHT) {
    console.log('处理顺子牌型');
    
    // 剩余牌按点数排序
    const sortedCards = [...remainingCards.value].sort((a, b) => 
      getRankValue(a.rank) - getRankValue(b.rank)
    );
    
    // 获取所有点数
    const ranks = sortedCards.map(card => getRankValue(card.rank));
    // 去重点数
    const uniqueRanks = Array.from(new Set(ranks)).sort((a, b) => a - b);
    console.log('剩余牌去重点数:', uniqueRanks);
    
    // 检查牌中是否有A
    const hasAce = uniqueRanks.includes(14);
    
    // 清空之前的选择
    selectedCards.value = [];
    
    // 特殊处理A-5顺子
    if (hasAce) {
      const hasLowStraight = [2, 3, 4, 5].every(value => uniqueRanks.includes(value));
      
      if (hasLowStraight) {
        console.log('检测到A-5顺子');
        
        // 找出对应的牌
        const aceCard = remainingCards.value.find(c => getRankValue(c.rank) === 14);
        const twoCard = remainingCards.value.find(c => getRankValue(c.rank) === 2);
        const threeCard = remainingCards.value.find(c => getRankValue(c.rank) === 3);
        const fourCard = remainingCards.value.find(c => getRankValue(c.rank) === 4);
        const fiveCard = remainingCards.value.find(c => getRankValue(c.rank) === 5);
        
        if (aceCard && twoCard && threeCard && fourCard && fiveCard) {
          selectedCards.value = [aceCard, twoCard, threeCard, fourCard, fiveCard];
          console.log('成功选择A-5顺子', selectedCards.value);
          return;
        }
      }
    }
    
    // 寻找顺子
    const findStraight = () => {
      // 检查每个可能的开始位置
      for (let i = 0; i < uniqueRanks.length - 4; i++) {
        let isConsecutive = true;
        
        // 检查从当前位置开始的5个点数是否连续
        for (let j = 0; j < 4; j++) {
          if (uniqueRanks[i + j + 1] !== uniqueRanks[i + j] + 1) {
            isConsecutive = false;
            break;
          }
        }
        
        if (isConsecutive) {
          const targetRanks = uniqueRanks.slice(i, i + 5);
          console.log('找到连续点数:', targetRanks);
          
          // 选择对应的牌
          const straights: Card[] = [];
          for (const rank of targetRanks) {
            const card = remainingCards.value.find(c => 
              getRankValue(c.rank) === rank && 
              !straights.some(s => s.suit === c.suit && s.rank === c.rank)
            );
            if (card) straights.push(card);
          }
          
          if (straights.length === 5) {
            selectedCards.value = straights;
            console.log('成功选择普通顺子', selectedCards.value);
            return true;
          }
        }
      }
      return false;
    };
    
    if (findStraight()) {
      return;
    }
    
    // 如果找不到合适的顺子，尝试普通方式
    console.log('未找到合适顺子，使用常规方法');
  }
  
  // 其他牌型使用原方法
  // 重新计算可能的牌型组合
  const possibleHands = getPossibleHands(remainingCards.value);
  
  // 按牌型分组
  const handsByType = new Map<HandType, Array<{ cards: Card[]; score: number }>>();
  possibleHands.forEach(hand => {
    if (!handsByType.has(hand.type)) {
      handsByType.set(hand.type, []);
    }
    handsByType.get(hand.type)?.push({ cards: hand.cards, score: hand.score });
  });
  
  // 转换为数组并排序
  const sortedHands = Array.from(handsByType.entries())
    .map(([type, hands]) => ({
      type,
      hands: hands.sort((a, b) => b.score - a.score)
    }))
    .sort((a, b) => b.type - a.type);
  
  // 更新可能的牌型
  possibleHandTypes.value = sortedHands;
  
  // 获取当前牌型的组合
  const group = sortedHands.find(group => group.type === type);
  if (group && group.hands.length > 0) {
    // 获取当前牌型的索引，如果没有则从0开始
    let currentIndex = currentHandTypeIndex.value.get(type) || 0;
    
    // 选择下一组牌（循环选择）
    currentIndex = (currentIndex + 1) % group.hands.length;
    currentHandTypeIndex.value.set(type, currentIndex);
    
    const cards = group.hands[currentIndex].cards;
    selectHandCombination(cards, type);
  }
};

// 选择特定的牌型组合
const selectHandCombination = (cards: Card[], type: HandType) => {
  // 清空之前的选择
  selectedCards.value = [];
  
  // 根据牌型选择关键牌
  let cardsToSelect: Card[] = [];
  switch (type) {
    case HandType.PAIR:
      // 选择组成对子的两张牌
      const rankCounts = new Map<number, Card[]>();
      cards.forEach(card => {
        const rankValue = getRankValue(card.rank);
        if (!rankCounts.has(rankValue)) {
          rankCounts.set(rankValue, []);
        }
        rankCounts.get(rankValue)?.push(card);
      });
      for (const [_, sameRankCards] of rankCounts) {
        if (sameRankCards.length >= 2) {
          cardsToSelect = sameRankCards.slice(0, 2);
          break;
        }
      }
      break;
      
    case HandType.TWO_PAIR:
      // 选择组成两对的四张牌
      const twoPairRanks = new Map<number, Card[]>();
      cards.forEach(card => {
        const rankValue = getRankValue(card.rank);
        if (!twoPairRanks.has(rankValue)) {
          twoPairRanks.set(rankValue, []);
        }
        twoPairRanks.get(rankValue)?.push(card);
      });
      const pairs = Array.from(twoPairRanks.values())
        .filter(sameRankCards => sameRankCards.length >= 2)
        .sort((a, b) => getRankValue(b[0].rank) - getRankValue(a[0].rank));
      
      if (pairs.length >= 2) {
        cardsToSelect = [...pairs[0].slice(0, 2), ...pairs[1].slice(0, 2)];
      }
      break;
      
    case HandType.THREE_OF_A_KIND:
      // 选择组成三条的三张牌
      const threeKindRanks = new Map<number, Card[]>();
      cards.forEach(card => {
        const rankValue = getRankValue(card.rank);
        if (!threeKindRanks.has(rankValue)) {
          threeKindRanks.set(rankValue, []);
        }
        threeKindRanks.get(rankValue)?.push(card);
      });
      for (const [_, sameRankCards] of threeKindRanks) {
        if (sameRankCards.length >= 3) {
          cardsToSelect = sameRankCards.slice(0, 3);
          break;
        }
      }
      break;
      
    case HandType.FOUR_OF_A_KIND:
      // 选择组成四条的四张牌
      const fourKindRanks = new Map<number, Card[]>();
      cards.forEach(card => {
        const rankValue = getRankValue(card.rank);
        if (!fourKindRanks.has(rankValue)) {
          fourKindRanks.set(rankValue, []);
        }
        fourKindRanks.get(rankValue)?.push(card);
      });
      for (const [_, sameRankCards] of fourKindRanks) {
        if (sameRankCards.length >= 4) {
          cardsToSelect = sameRankCards.slice(0, 4);
          break;
        }
      }
      break;
      
    case HandType.FULL_HOUSE:
      // 选择组成葫芦的三张牌和两张牌
      const fullHouseRanks = new Map<number, Card[]>();
      cards.forEach(card => {
        const rankValue = getRankValue(card.rank);
        if (!fullHouseRanks.has(rankValue)) {
          fullHouseRanks.set(rankValue, []);
        }
        fullHouseRanks.get(rankValue)?.push(card);
      });
      const threeKind = Array.from(fullHouseRanks.values())
        .find(sameRankCards => sameRankCards.length >= 3);
      const pair = Array.from(fullHouseRanks.values())
        .find(sameRankCards => sameRankCards.length >= 2 && sameRankCards !== threeKind);
      
      if (threeKind && pair) {
        cardsToSelect = [...threeKind.slice(0, 3), ...pair.slice(0, 2)];
      }
      break;
      
    case HandType.STRAIGHT:
    case HandType.STRAIGHT_FLUSH:
    case HandType.ROYAL_FLUSH:
      // 选择顺子的五张牌
      if (type === HandType.STRAIGHT_FLUSH || type === HandType.ROYAL_FLUSH) {
        // 对于同花顺和皇家同花顺，直接选择提供的牌
        cardsToSelect = cards;
        
        // 特别处理 A2345 同花顺，确保选中 Ace
        const hasAce = cards.some(card => card.rank === 'ACE');
        const hasTwo = cards.some(card => card.rank === 'TWO');
        
        if (hasAce && hasTwo) {
          // 如果是 A2345 同花顺，确保 Ace 被选中
          // 在 remainingCards 中找到对应的 Ace 牌
          const suit = cards[0].suit; // 所有牌都是同一花色
          const aceCard = remainingCards.value.find(c => c.rank === 'ACE' && c.suit === suit);
          
          if (aceCard) {
            // 确保 Ace 在选择的牌中
            const otherCards = cards.filter(card => card.rank !== 'ACE')
              .slice(0, 4); // 只取四张非 Ace 的牌
            
            cardsToSelect = [aceCard, ...otherCards];
          }
        }
      } else {
        // 对于普通顺子，保持原有逻辑
        const ranks = cards.map(card => getRankValue(card.rank)).sort((a, b) => a - b);
        if (ranks.includes(14)) { // 如果有A
          const lowAceRanks = [...ranks.filter(r => r !== 14), 1].sort((a, b) => a - b);
          if (lowAceRanks[4] - lowAceRanks[0] === 4) {
            cardsToSelect = cards.filter(card => 
              lowAceRanks.includes(getRankValue(card.rank))
            );
          }
        } else if (ranks[4] - ranks[0] === 4) {
          cardsToSelect = cards;
        }
      }
      break;
      
    case HandType.FLUSH:
      // 选择同花的五张牌
      const suits = new Map<string, Card[]>();
      cards.forEach(card => {
        if (!suits.has(card.suit)) {
          suits.set(card.suit, []);
        }
        suits.get(card.suit)?.push(card);
      });
      const flushCards = Array.from(suits.values())
        .find(sameSuitCards => sameSuitCards.length >= 5);
      if (flushCards) {
        cardsToSelect = flushCards.slice(0, 5);
      }
      break;
      
    default:
      // 对于其他牌型，选择所有牌
      cardsToSelect = cards;
  }
  
  // 选中新的牌
  cardsToSelect.forEach(card => {
    const matchingCard = remainingCards.value.find(c => 
      c.suit === card.suit && c.rank === card.rank
    );
    if (matchingCard) {
      selectedCards.value.push(matchingCard);
    }
  });
};

// 检查是否有特定牌型
const hasHandType = (type: HandType): boolean => {
  return possibleHandTypes.value.some(group => group.type === type);
};

// 获取特定牌型的数量
const getHandTypeCount = (type: HandType): number => {
  const group = possibleHandTypes.value.find(group => group.type === type);
  return group ? group.hands.length : 0;
};

// 获取特定牌型的最高分数
const getHandTypeMaxScore = (type: HandType): number => {
  const group = possibleHandTypes.value.find(group => group.type === type);
  return group ? group.hands[0]?.score || 0 : 0;
};

// 添加计算属性判断是否有任何已选牌
const hasAnyCards = computed(() => {
  return frontHand.value.length > 0 || 
         middleHand.value.length > 0 || 
         backHand.value.length > 0;
});

// 获取结算结果
const getSettlementResults = async () => {
  try {
    const result = await roomApi.getRoomStatus(roomCode.value);
    if (result && result.data) {
      const allPlayersReady = result.data.players.every((p: any) => p.ready);
      
      // 如果所有玩家都已准备且结算数据存在
      if (allPlayersReady && 
          result.data.roundScores && 
          Object.keys(result.data.roundScores).length > 0 && 
          roomStatus.value === 'PLAYING') {
        
        roundScores.value = result.data.roundScores;
        
        // 构建结算结果数据
        gameResult.value = result.data.players.map((p: any) => ({
          id: p.id,
          nickname: p.nickname,
          score: p.score,
          roundScore: result.data.roundScores?.[p.id] || 0
        })).sort((a: {score: number}, b: {score: number}) => b.score - a.score);
        
        console.log("手动获取结算结果", gameResult.value);
        showSettlementDialog();
        
        // 添加重试机制，确保结算结果总是会显示
        return true;
      }
    }
    return false;
  } catch (error) {
    console.error('获取结算结果失败:', error);
    return false;
  }
};

// 监听roundScores变化
watch(roundScores, (newValue, oldValue) => {
  // 只有在roundScores从空变为有值、且游戏状态为PLAYING时，才尝试显示结算结果
  if (Object.keys(newValue).length > 0 && 
      Object.keys(oldValue).length === 0 && 
      roomStatus.value === 'PLAYING') {
    console.log("监听到roundScores首次变化，尝试显示结算结果");
    
    // 添加重试机制，最多尝试3次
    let retryCount = 0;
    const maxRetries = 3;
    
    const tryShowSettlement = async () => {
      // 检查对话框是否已经显示，避免重复显示
      if (showResultDialog.value) {
        console.log("结算对话框已经显示，不再重试");
        return;
      }
      
      const success = await getSettlementResults();
      if (!success && retryCount < maxRetries) {
        retryCount++;
        console.log(`显示结算结果失败，尝试重试(${retryCount}/${maxRetries})...`);
        setTimeout(tryShowSettlement, 1000);
      }
    };
    
    tryShowSettlement();
  }
}, { deep: true });

// 重置单个墩位的牌
const resetHand = (hand: 'front' | 'middle' | 'back') => {
  // 将墩位中的牌返回到可选牌中
  switch (hand) {
    case 'front':
      frontHand.value.forEach(card => {
        if (!selectedCards.value.some(c => c.suit === card.suit && c.rank === card.rank)) {
          selectedCards.value.push(card);
        }
      });
      frontHand.value = [];
      break;
    case 'middle':
      middleHand.value.forEach(card => {
        if (!selectedCards.value.some(c => c.suit === card.suit && c.rank === card.rank)) {
          selectedCards.value.push(card);
        }
      });
      middleHand.value = [];
      break;
    case 'back':
      backHand.value.forEach(card => {
        if (!selectedCards.value.some(c => c.suit === card.suit && c.rank === card.rank)) {
          selectedCards.value.push(card);
        }
      });
      backHand.value = [];
      break;
  }
  
  // 重新计算可能的牌型
  const possibleHands = getPossibleHands(remainingCards.value);
  
  // 按牌型分组
  const handsByType = new Map<HandType, Array<{ cards: Card[]; score: number }>>();
  possibleHands.forEach(hand => {
    if (!handsByType.has(hand.type)) {
      handsByType.set(hand.type, []);
    }
    handsByType.get(hand.type)?.push({ cards: hand.cards, score: hand.score });
  });
  
  // 转换为数组并排序
  const sortedHands = Array.from(handsByType.entries())
    .map(([type, hands]) => ({
      type,
      hands: hands.sort((a, b) => b.score - a.score)
    }))
    .sort((a, b) => b.type - a.type);
  
  // 更新可能的牌型
  possibleHandTypes.value = sortedHands;
};

// 重置所有墩位的牌
const resetAllHands = () => {
  // 将所有墩位中的牌返回到可选牌中
  [...frontHand.value, ...middleHand.value, ...backHand.value].forEach(card => {
    if (!selectedCards.value.some(c => c.suit === card.suit && c.rank === card.rank)) {
      selectedCards.value.push(card);
    }
  });
  
  // 清空所有墩位
  frontHand.value = [];
  middleHand.value = [];
  backHand.value = [];
  
  // 重新计算可能的牌型
  const possibleHands = getPossibleHands(remainingCards.value);
  
  // 按牌型分组
  const handsByType = new Map<HandType, Array<{ cards: Card[]; score: number }>>();
  possibleHands.forEach(hand => {
    if (!handsByType.has(hand.type)) {
      handsByType.set(hand.type, []);
    }
    handsByType.get(hand.type)?.push({ cards: hand.cards, score: hand.score });
  });
  
  // 转换为数组并排序
  const sortedHands = Array.from(handsByType.entries())
    .map(([type, hands]) => ({
      type,
      hands: hands.sort((a, b) => b.score - a.score)
    }))
    .sort((a, b) => b.type - a.type);
  
  // 更新可能的牌型
  possibleHandTypes.value = sortedHands;
};

// 定时更新房间状态
let statusTimer: number;
let webSocketSubscription: any = null;

onMounted(() => {
  getUserInfo();
  
  // 初始化结算提示音
  try {
    settlementSound.value = new Audio('/sounds/settlement.mp3');
  } catch (e) {
    console.error('初始化提示音失败:', e);
  }
  
  // 在获取用户信息后连接WebSocket
  const setupWebSocket = async () => {
    await getUserInfo();
    if (userInfo.value?.id) {
      const { connected, subscribe } = useWebSocket();
      
      // 等待WebSocket连接完成
      const checkConnection = () => {
        if (connected.value) {
          webSocketSubscription = subscribe(
            `/user/${userInfo.value.id}/queue/room-status`,
            handleRoomStatusUpdate
          );
          console.log('WebSocket已订阅房间状态更新');
        } else {
          setTimeout(checkConnection, 1000);
        }
      };
      
      checkConnection();
    }
  };
  
  setupWebSocket();
  getRoomStatus();
  statusTimer = window.setInterval(getRoomStatus, 5000); // 每5秒更新一次状态
});

onUnmounted(() => {
  if (statusTimer) {
    clearInterval(statusTimer);
  }
  
  // 取消WebSocket订阅
  if (webSocketSubscription) {
    webSocketSubscription.unsubscribe();
    console.log('已取消WebSocket订阅');
  }
});

// 播放结算提示音
const playSettlementSound = () => {
  if (settlementSound.value) {
    settlementSound.value.currentTime = 0;
    settlementSound.value.play().catch(e => {
      console.error('播放提示音失败:', e);
    });
  }
};

// 显示结算对话框
const showSettlementDialog = () => {
  console.log('显示结算对话框');
  
  // 延迟一点显示结算对话框，确保WebSocket消息处理完毕
  setTimeout(() => {
    showResultDialog.value = true;
    
    // 尝试播放提示音
    try {
      playSettlementSound();
    } catch (e) {
      console.error('播放提示音失败:', e);
    }
    
    // 使用Element Plus的消息通知
    ElMessage({
      message: '本回合已结算，请查看结果',
      type: 'success',
      duration: 5000, // 延长显示时间
      showClose: true
    });
  
    // 再次确保对话框显示
    setTimeout(() => {
      if (!showResultDialog.value) {
        console.log('对话框未显示，尝试再次显示');
        showResultDialog.value = true;
      }
    }, 500);
  }, 200);
};

// 处理WebSocket接收到的房间状态更新
const handleRoomStatusUpdate = (data: any) => {
  console.log('收到WebSocket房间状态更新:', data);
  
  // 更详细的调试日志
  console.log(`房间状态: ${data.status}, 当前回合: ${data.currentRound}/${data.totalRounds}`);
  console.log(`玩家数: ${data.players.length}, 已准备人数: ${data.readyPlayersCount}`);
  console.log(`本回合得分数据:`, data.roundScores);
  
  // 检查状态变化 - 保存旧状态用于比较
  const oldStatus = roomStatus.value;
  const oldRound = currentRound.value;
  
  // 如果从PLAYING变回WAITING状态且是第一回合，重置游戏开始标记
  if (oldStatus === 'PLAYING' && data.status === 'WAITING' && data.currentRound === 1) {
    console.log("重置游戏开始提示标记 (WebSocket)");
    showGameStartedFlag.value = false;
  }
  
  // 更新房间状态
  roomStatus.value = data.status;
  otherPlayers.value = data.players.filter((p: any) => p.id !== userInfo.value?.id);
  readyPlayersCount.value = data.readyPlayersCount || 0;
  totalPlayers.value = data.totalPlayers || 0;
  currentRound.value = data.currentRound || 1;
  totalRounds.value = data.totalRounds || 13;
  
  // 检查是否为游戏开始的状态：第一回合且状态为PLAYING
  if (data.status === 'PLAYING' && data.currentRound === 1) {
    // 如果是新状态(从等待到游戏中)或还未显示过提示
    if (oldStatus === 'WAITING' || !showGameStartedFlag.value) {
      console.log("显示游戏开始提示 (WebSocket)");
      showGameStartDialog.value = true;
      setTimeout(() => {
        showGameStartDialog.value = false;
      }, 1000); // 1秒后自动关闭
      
      // 标记已经显示过游戏开始提示
      showGameStartedFlag.value = true;
    }
  }
  
  // 获取当前玩家信息
  const currentPlayer = data.players.find((p: any) => p.id === userInfo.value?.id);
  if (currentPlayer) {
    isReady.value = currentPlayer.ready || false;
    isCreator.value = data.players[0].id === userInfo.value?.id;
    
    // 当状态为 PLAYING 时，检查是否有牌
    if (data.status === 'PLAYING') {
      console.log("游戏进行中，玩家卡牌:", currentPlayer.cards);
      
      // 如果玩家有牌，说明游戏刚开始
      if (currentPlayer.cards && currentPlayer.cards.length > 0) {
        // 更新玩家卡牌
        myCards.value = currentPlayer.cards || [];
        hasSubmittedThisRound.value = false; // 确保开始新回合时提交状态为未提交
        
        // 重置墩位选择
        resetAllHands();
        
        // 更新可能的牌型
        updatePossibleHandTypes();
        
        // 通知用户游戏已开始
        ElMessage({
          message: `第${data.currentRound}回合开始，请组织您的牌型`,
          type: 'success',
          duration: 5000,
          showClose: true
        });
      }
      
      // 如果当前玩家已准备且游戏正在进行中，标记为已提交本轮牌型
      if (isReady.value) {
        hasSubmittedThisRound.value = true;
      }
    } 
    
    // 当状态变为WAITING且回合大于1时，说明是回合结束后等待重新准备
    if (data.status === 'WAITING' && data.currentRound > 1) {
      console.log('回合结束，等待重新准备开始下一回合');
      
      // 显示准备提示，但只在未准备时显示
      if (!isReady.value) {
        hasSubmittedThisRound.value = false;
        ElMessage({
          message: `第${data.currentRound-1}回合已结束，请准备开始第${data.currentRound}回合`,
          type: 'info',
          duration: 5000,
          showClose: true
        });
      }
      
      // 不管是否已准备，都重置牌型选择
      resetAllHands();
    }
  }
  
  // 检查结算状态 - 增强检测逻辑
  if (data.roundScores && Object.keys(data.roundScores).length > 0) {
    console.log('检测到回合得分数据:', data.roundScores);
    
    // 只有在第一次接收到得分数据时才更新和显示
    if (Object.keys(roundScores.value).length === 0) {
      console.log('首次接收得分数据，准备显示结算对话框');
      roundScores.value = data.roundScores;
      
      // 检查是否所有玩家都已准备
      const allReady = data.players.every((p: any) => p.ready);
      console.log(`所有玩家是否已准备: ${allReady}`);
      
      // 必须满足以下条件才显示结算对话框:
      // 1. 所有玩家都已准备
      // 2. 有得分数据
      // 3. 游戏状态为PLAYING或WAITING（表示刚结算完）
      if (allReady && (data.status === 'PLAYING' || data.status === 'WAITING') && !showResultDialog.value) {
        // 构建结算结果数据
        gameResult.value = data.players.map((p: any) => ({
          id: p.id,
          nickname: p.nickname,
          score: p.score,
          roundScore: data.roundScores?.[p.id] || 0
        })).sort((a: {score: number}, b: {score: number}) => b.score - a.score);
        
        console.log('准备显示结算对话框，得分数据:', gameResult.value);
        showSettlementDialog();
      }
    } else {
      console.log('已经接收过得分数据，不再重复显示');
    }
  } else if (data.status === 'PLAYING' && Object.keys(data.roundScores || {}).length === 0) {
    // 清空得分数据，这样在下一轮时才能正确显示
    console.log('清空上一轮的得分数据');
    roundScores.value = {};
  }
};

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'WAITING':
      return 'success'
    case 'PLAYING':
      return 'warning'
    case 'FINISHED':
      return 'info'
    default:
      return ''
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'WAITING':
      return '等待中'
    case 'PLAYING':
      return '游戏中'
    case 'FINISHED':
      return '已结束'
    default:
      return status
  }
}

// 更新可能的牌型
const updatePossibleHandTypes = () => {
  if (myCards.value.length === 0) return;
  
  // 重新计算可能的牌型
  const possibleHands = getPossibleHands(remainingCards.value);
  
  // 按牌型分组
  const handsByType = new Map<HandType, Array<{ cards: Card[]; score: number }>>();
  possibleHands.forEach(hand => {
    if (!handsByType.has(hand.type)) {
      handsByType.set(hand.type, []);
    }
    handsByType.get(hand.type)?.push({ cards: hand.cards, score: hand.score });
  });
  
  // 转换为数组并排序
  const sortedHands = Array.from(handsByType.entries())
    .map(([type, hands]) => ({
      type,
      hands: hands.sort((a, b) => b.score - a.score)
    }))
    .sort((a, b) => b.type - a.type);
  
  // 更新可能的牌型
  possibleHandTypes.value = sortedHands;
};

// 添加移动端优化相关的变量
const activeCollapse = ref(['cards', 'hands', 'handTypes']); // 默认展开所有区域

// 可用牌型数量计算属性
const availableHandTypesCount = computed(() => {
  return Object.values(HandType)
    .filter((t): t is HandType => typeof t === 'number' && t !== HandType.HIGH_CARD)
    .filter(type => hasHandType(type))
    .length;
});

// 关闭结算结果对话框
const closeResultDialog = () => {
  showResultDialog.value = false;
  
  // 如果是等待状态且未准备，提示用户准备
  if (roomStatus.value === 'WAITING' && !isReady.value && currentRound.value > 1) {
    ElMessage({
      message: '请点击"准备下一回合"按钮开始新的回合',
      type: 'info',
      duration: 5000
    });
  }
}

// 关闭游戏开始提示对话框
const closeGameStartDialog = () => {
  showGameStartDialog.value = false;
}

</script>

<style scoped>
.game-container {
  min-height: 100vh;
  background-color: #f0f2f5;
  background-image: linear-gradient(135deg, #f0f2f5 25%, #e9ecef 25%, #e9ecef 50%, #f0f2f5 50%, #f0f2f5 75%, #e9ecef 75%, #e9ecef 100%);
  background-size: 40px 40px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  border-bottom: 1px solid #ddd;
  padding: 0 15px;
}

.room-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.room-info h2 {
  margin: 0;
}

.user-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.game-table {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.game-status {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
}

.current-player {
  text-align: center;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.player-info {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
  margin-bottom: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 5px 10px;
  border-radius: 5px;
}

.player-cards {
  min-height: 120px;
  background-color: rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: linear-gradient(45deg, rgba(0, 128, 0, 0.2) 25%, transparent 25%, transparent 50%, rgba(0, 128, 0, 0.2) 50%, rgba(0, 128, 0, 0.2) 75%, transparent 75%, transparent);
  background-size: 20px 20px;
}

.player-hands {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.hand-section {
  text-align: center;
  min-width: 180px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10px;
  padding: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
}

.hand-section h3 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0;
  font-size: 16px;
}

.hand-count {
  font-size: 14px;
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
  padding: 2px 6px;
  border-radius: 10px;
}

.hand-section.selected {
  background-color: rgba(64, 158, 255, 0.1);
  border: 2px solid #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.hand-section:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px 0 rgba(0, 0, 0, 0.15);
}

.cards-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
  padding: 10px;
  margin: 0 auto;
}

.player-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  width: 100%;
}

/* 移动端优化样式 */
.mobile-header {
  padding: 0;
}

.mobile-main {
  padding: 10px;
}

.mobile-collapse {
  margin-top: 10px;
  background: transparent;
  border: none;
}

.collapse-section {
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  font-weight: bold;
}

.ultra-compact-cards {
  min-height: auto;
  padding: 3px;
  margin-bottom: 5px;
}

.ultra-compact-hands {
  margin-top: 0;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.ultra-compact-hands .hand-section {
  width: auto;
  min-width: auto;
  padding: 5px;
  margin-bottom: 5px;
}

.ultra-compact-hands .cards-container {
  padding: 3px;
  gap: 2px;
}

.mini-cards {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 2px;
}

.tiny-hand-type {
  padding: 8px;
  font-size: 14px;
  height: 30px;
  margin-bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.5);
  transition: all 0.3s;
  cursor: pointer;
  color: #909399;
}

.tiny-hand-type.available {
  background-color: rgba(64, 158, 255, 0.1);
  border-color: #409EFF;
  color: #409EFF;
  font-weight: 500;
}

.tiny-hand-type:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.hand-type-name {
  font-size: 14px;
}

.hand-types-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 5px;
  padding: 3px;
}

@media screen and (max-width: 768px) {
  .mobile-collapse {
    margin-top: 5px;
  }
  
  .game-table {
    padding: 5px;
    gap: 10px;
  }
  
  .player-info {
    flex-wrap: wrap;
    margin-bottom: 5px;
    padding: 3px 5px;
  }
  
  .player-actions {
    margin-top: 10px;
  }
  
  .current-player {
    padding: 10px 5px;
  }
  
  .game-status {
    margin-bottom: 10px;
  }
  
  .hand-section h3 {
    margin: 0 0 5px 0;
    font-size: 14px;
  }
  
  .hand-count {
    font-size: 12px;
    padding: 1px 4px;
  }
  
  .section-title {
    font-size: 14px;
  }
  
  .collapse-section :deep(.el-collapse-item__header) {
    padding: 0 8px;
    height: 40px;
    line-height: 40px;
  }
  
  .collapse-section :deep(.el-collapse-item__content) {
    padding-bottom: 5px;
  }
  
  .hand-type-name {
    font-size: 12px;
  }
  
  .room-info h2 {
    font-size: 16px;
  }
  
  .user-dropdown {
    font-size: 14px;
  }
  
  .player-actions {
    flex-direction: column;
    align-items: center;
  }
  
  /* 针对小屏幕的卡片大小调整 */
  :deep(.el-card.is-always-shadow) {
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  /* 结算对话框移动端样式 */
  .settlement-dialog {
    margin: 0 !important;
  }
  
  .settlement-dialog :deep(.el-dialog__body) {
    padding: 0;
    max-height: calc(100vh - 100px);
    overflow-y: auto;
  }
  
  /* 添加针对紧凑信息和增强卡片区域的移动端样式 */
  .compact-info {
    margin-bottom: 3px;
    padding: 2px 5px;
  }
  
  .user-nickname {
    font-size: 13px;
  }
  
  .user-stats :deep(.el-tag) {
    transform: scale(0.9);
    transform-origin: right center;
  }
  
  .enhanced-card-area {
    min-height: 100px;
  }
  
  .mini-cards {
    padding: 5px;
    justify-content: flex-start;
  }
}

/* 结算对话框样式 - 保持不变 */
.settlement-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.settlement-dialog :deep(.el-dialog__header) {
  padding: 15px;
  background: linear-gradient(135deg, #409eff, #17ead9);
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.settlement-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  text-align: center;
}

.result-content {
  display: flex;
  flex-direction: column;
  padding: 0;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

.result-round {
  margin: 0;
  color: #409eff;
  font-size: 18px;
}

.round-indicator {
  background-color: #409eff;
  color: white;
  padding: 4px 12px;
  border-radius: 15px;
  font-weight: 500;
}

.round-indicator span {
  font-size: 18px;
  font-weight: 700;
}

.players-list {
  padding: 15px;
  min-height: 200px;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  margin-bottom: 8px;
  background-color: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.result-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.player-rank {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e6e6e6;
  color: #666;
  border-radius: 50%;
  font-weight: 600;
  margin-right: 15px;
}

.first-place .player-rank {
  background-color: #f5c518;
  color: white;
}

.result-item.current-player {
  background-color: #ecf5ff;
  border-left: 4px solid #409eff;
}

.player-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.nickname {
  font-weight: 600;
  color: #333;
}

.score {
  font-size: 20px;
  font-weight: 700;
  color: #409eff;
  margin-top: 4px;
}

.round-score {
  font-size: 18px;
  font-weight: 600;
  padding: 4px 10px;
  border-radius: 4px;
  background-color: #f5f5f5;
}

.round-score.positive {
  color: #67c23a;
}

.round-score.negative {
  color: #f56c6c;
}

.next-round-info {
  text-align: center;
  padding: 10px;
  color: #909399;
  font-size: 14px;
  background-color: #f8f9fa;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 10px 0;
}

/* 列表动画 */
.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

.submitted-hint {
  margin-top: 10px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 5px;
  text-align: center;
}

.hint-text {
  margin: 5px 0 0 0;
  font-size: 14px;
  color: #606266;
}

.next-round-reminder {
  margin-bottom: 15px;
  width: 100%;
}

/* 添加全屏对话框选项 */
.fullscreen-on-mobile {
  width: 100% !important;
  margin: 0 !important;
}

.compact-info {
  flex-direction: row;
  justify-content: space-between;
  padding: 3px 8px;
  margin-bottom: 5px;
  gap: 5px;
}

.user-nickname {
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

.user-stats {
  display: flex;
  gap: 5px;
  align-items: center;
}

.enhanced-card-area {
  min-height: 80px;
  padding: 5px;
  margin-bottom: 5px;
  background-image: linear-gradient(45deg, rgba(0, 128, 0, 0.1) 25%, transparent 25%, transparent 50%, rgba(0, 128, 0, 0.1) 50%, rgba(0, 128, 0, 0.1) 75%, transparent 75%, transparent);
  background-size: 15px 15px;
}

/* 游戏开始提示对话框样式 */
.game-start-dialog {
  margin: 0 !important;
}

.game-start-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.game-start-dialog :deep(.el-dialog__header) {
  padding: 15px;
  background: linear-gradient(135deg, #409eff, #17ead9);
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.game-start-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  text-align: center;
}

.game-start-content {
  padding: 20px;
}

/* 新的游戏开始提示样式 */
.game-start-notification {
  position: fixed;
  top: 50px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  animation: slideDown 0.3s ease-in-out, fadeOut 0.3s ease-in-out 0.7s forwards;
}

.game-start-text {
  font-size: 32px;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 0 10px #409eff, 0 0 20px #409eff;
  font-family: "黑体", "SimHei", "STHeiti", sans-serif;
  letter-spacing: 4px;
  background: linear-gradient(135deg, #409eff, #17ead9);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  padding: 10px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  background-color: #fff;
}

@keyframes slideDown {
  0% {
    transform: translate(-50%, -50px);
  }
  100% {
    transform: translate(-50%, 0);
  }
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.game-start-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style> 
